/**
 * 公共JavaScript库
 * 包含所有页面共用的工具函数
 */

// 格式化成交量
function formatVolume(volume) {
    if (!volume) return '0';
    if (volume >= 100000000) {
        return (volume / 100000000).toFixed(1) + '亿';
    } else if (volume >= 10000) {
        return (volume / 10000).toFixed(1) + '万';
    }
    return volume.toString();
}

// 格式化金额
function formatAmount(amount) {
    if (!amount) return '0';
    if (amount >= 100000000) {
        return (amount / 100000000).toFixed(2) + '亿';
    } else if (amount >= 10000) {
        return (amount / 10000).toFixed(2) + '万';
    }
    return amount.toFixed(2);
}

// 格式化市值
function formatMarketCap(marketCap) {
    if (!marketCap) return '0';
    if (marketCap >= 100000000) {
        return (marketCap / 100000000).toFixed(1) + '亿';
    } else if (marketCap >= 10000) {
        return (marketCap / 10000).toFixed(1) + '万';
    }
    return marketCap.toString();
}

// 格式化涨停时间
function formatLimitUpTime(timeStr) {
    if (!timeStr || timeStr === '未知') return '-:-:-';
       
    // 处理 HHMMSSsss 格式
    if (timeStr.length === 9) {
        const hour = parseInt(timeStr.substring(0, 2));
        const minute = timeStr.substring(2, 4);
        const second = timeStr.substring(4, 6);
        return `${hour}:${minute}:${second}`;
    }
    // 处理 HMMSSsss 格式 (如: 93000000)
    else if (timeStr.length === 8) {
        const hour = parseInt(timeStr.substring(0, 1));
        const minute = timeStr.substring(1, 3);
        const second = timeStr.substring(3, 5);
        return `0${hour}:${minute}:${second}`;
    }
    
    return timeStr || '-:-:-';
}

// 通用API请求函数
async function apiRequest(url, options = {}) {
    try {
        const response = await fetch(url, {
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            },
            ...options
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        return await response.json();
    } catch (error) {
        console.error('API请求失败:', error);
        throw error;
    }
}

// 通用分页函数
function updatePagination(currentPage, totalPages, onPageChange) {
    const paginationContainer = document.querySelector('.pagination');
    if (!paginationContainer) return;
    
    paginationContainer.innerHTML = '';
    
    // 上一页按钮
    const prevBtn = document.createElement('button');
    prevBtn.className = 'pagination-btn';
    prevBtn.disabled = currentPage <= 1;
    prevBtn.innerHTML = '<i class="fas fa-chevron-left"></i>';
    prevBtn.onclick = () => onPageChange(currentPage - 1);
    paginationContainer.appendChild(prevBtn);
    
    // 页码按钮
    const startPage = Math.max(1, currentPage - 2);
    const endPage = Math.min(totalPages, currentPage + 2);
    
    for (let i = startPage; i <= endPage; i++) {
        const pageBtn = document.createElement('button');
        pageBtn.className = `pagination-btn ${i === currentPage ? 'active' : ''}`;
        pageBtn.textContent = i;
        pageBtn.onclick = () => onPageChange(i);
        paginationContainer.appendChild(pageBtn);
    }
    
    // 下一页按钮
    const nextBtn = document.createElement('button');
    nextBtn.className = 'pagination-btn';
    nextBtn.disabled = currentPage >= totalPages;
    nextBtn.innerHTML = '<i class="fas fa-chevron-right"></i>';
    nextBtn.onclick = () => onPageChange(currentPage + 1);
    paginationContainer.appendChild(nextBtn);
}

// 通用加载状态管理
function showLoading(container, message = '加载中...') {
    if (container) {
        container.innerHTML = `<div class="loading-message">${message}</div>`;
    }
}

function hideLoading(container) {
    if (container) {
        const loadingElement = container.querySelector('.loading-message');
        if (loadingElement) {
            loadingElement.remove();
        }
    }
}

// 通用错误处理
function showError(container, message = '加载失败') {
    if (container) {
        container.innerHTML = `<div class="error-message">${message}</div>`;
    }
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 日期格式化
function formatDate(dateString) {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
}

// 时间格式化
function formatTime(timeString) {
    if (!timeString) return '-';
    const date = new Date(timeString);
    return date.toLocaleTimeString('zh-CN');
}
